package com.pv.bfc.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.pv.bfc.dao.FolderRepository;
import com.pv.bfc.model.Folder;
import com.pv.bfc.utils.GetUserDetailsFromContext;
import com.pv.bfc.web.validator.FolderValidator;

@SuppressWarnings("deprecation")
public class CreateFolderController extends SimpleFormController {

	private static final Log logger = LogFactory
			.getLog(CreateFolderController.class);

	private static final String FOLDER_ID = "folderid";

	private FolderRepository folderRepo;

	private GetUserDetailsFromContext usrDtls;

	private String[] labels;

	public CreateFolderController() {
		setCommandClass(Folder.class);
		setSuccessView("redirect:folders.htm");
		setValidator(new FolderValidator());
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		CustomDateEditor dateEditor = new CustomDateEditor(
				new SimpleDateFormat("dd-MMM-yyyy"), true);
		binder.registerCustomEditor(Date.class, dateEditor);
	}

	@Override
	protected Map<String, Object> referenceData(HttpServletRequest request)
			throws Exception {
		return new ModelMap("labels", labels);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer id = ServletRequestUtils.getIntParameter(request, FOLDER_ID);

		/*
		 * HttpSession session = request.getSession(); SecurityContext ctx2 =
		 * (SecurityContext) session .getAttribute("SPRING_SECURITY_CONTEXT");
		 * Authentication auth2 = ctx2.getAuthentication();
		 * System.out.println("### User Name 3 - " + auth2.getPrincipal());
		 */

		if (id != null && !"".equals(id)) {
			return folderRepo.retrieveFolderById(id);
		} else {
			return super.formBackingObject(request);
		}
	}

	@Override
	protected void doSubmitAction(Object folder) throws Exception {
		logger.info("IN CreateFolderController - doSubmitAction");
		Folder fold = (Folder) folder;
		logger.info("User Name - " + usrDtls.getUserName());
		fold.setUserName(usrDtls.getUserName());
		folderRepo.persistFolder((Folder) folder);
		logger.info("OUT CreateFolderController - doSubmitAction");
	}

	public void setFolderRepo(FolderRepository folderRepo) {
		this.folderRepo = folderRepo;
	}

	public void setLabels(String[] labels) {
		this.labels = labels;
	}

	public void setusrDtls(GetUserDetailsFromContext usrDtls) {
		this.usrDtls = usrDtls;
	}
}
